package com.h.forum.services.impl;

import com.h.forum.common.constant.Constants;
import com.h.forum.common.enums.ResultCode;
import com.h.forum.common.utils.StringUtil;
import com.h.forum.dao.MessageMapper;
import com.h.forum.exception.ApplicationException;
import com.h.forum.pojo.model.Message;
import com.h.forum.pojo.response.AppResult;
import com.h.forum.pojo.response.UserInfoResponse;
import com.h.forum.services.IMessageService;
import com.h.forum.services.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MessageMapper messageMapper;

    @Resource(name = "userServiceImpl")
    private IUserService userService;

    /**
     * 发送站内信息
     * @param message
     */
    @Override
    public void create(Message message) {
        if (message == null
                || message.getPostUserId() == null
                || message.getReceiveUserId() == null
                || StringUtil.isEmpty(message.getContent())) {
            // 为空
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验接受者是否存在
        UserInfoResponse userInfo = userService.selectById(message.getReceiveUserId());
        if (userInfo == null) {
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 设置默认值
        message.setState((byte) 0); // 表示未读状态
        message.setDeleteState((byte) 0);
        // 设置创建与更新时间
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);

        // 调用DAO层
        int row = messageMapper.insertSelective(message);
        if (row != 1) {
            // 说明错误，打印日志，抛出异常
            log.error(ResultCode.FAILED_CREATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
    }

    /**
     * 根据用户Id，查询未读数
     * @param receiveUserId
     * @return
     */
    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Integer count = messageMapper.selectUnreadCount(receiveUserId);
        if (count == null) {

            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }

        return count;
    }

    /**
     * 查询站内信列表
     * @param receiveUserId
     * @return
     */
    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);

        return messages;
    }

    /**
     * 更新指定站内信的状态
     * @param id
     * @param state
     */
    @Override
    public void updateStateById(Long id, Byte state) {
        // 非空校验, state : 0 未读 1 已读 2 已回复
        if (id == null || id <= 0 || state < 0 || state > 2) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 构造更新对象
        Message message = new Message();
        message.setId(id);
        message.setState(state);
        Date date = new Date();
        message.setUpdateTime(date);

        // 调用Service层
        int row = messageMapper.updateByPrimaryKeySelective(message);
        if (row != 1) {
            // 说明错误，打印日志，抛出异常
            log.error(ResultCode.FAILED_CREATE.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
    }

    /**
     * 根据ID查询对应的站内信息
     * @param id
     * @return
     */
    @Override
    public Message selectById(Long id) {
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Message message = messageMapper.selectByPrimaryKey(id);

        return message;
    }

    /**
     * 回复站内信
     * @param repliedId
     * @param message
     */
    @Override
    public void reply(Long repliedId, Message message) {
        if (repliedId == null || repliedId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据站内信Id，查询对应的信息
        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);
        if (existsMessage == null
                || existsMessage.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        // 更新为已经回复的状态
        updateStateById(repliedId,(byte) 2);

        // 将回复的信息写入到数据库中
        create(message);
    }

}
